package gcosc.fun.hly.fastsso.utils;

import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class RedisUtil {

    private final StringRedisTemplate redisTemplate;

    public <T> T get(String key, Class<T> c) {
        String json = redisTemplate.opsForValue().get(key);
        if (json == null){
            return null;
        }
        return JSON.parseObject(json, c);
    }

    public String getString(String key) {
        String json = redisTemplate.opsForValue().get(key);
        if (json == null){
            return null;
        }
        return JSON.parseObject(json, String.class);
    }

    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    public void set(String key, Object o) {
        redisTemplate.opsForValue().set(key, JSON.toJSONString(o));
    }

    public void set(String key, Object o, Long time) {
        redisTemplate.opsForValue().set(key, JSON.toJSONString(o), time, TimeUnit.SECONDS);
    }

    public void set(String key, Object o, Long time, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, JSON.toJSONString(o), time, unit);
    }
}
